package com.tanhua.dubbo.api;

import com.tanhua.model.domain.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.*;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/12/7 13:53
 */
@DubboService
public class UserLikeApiImpl implements UserLikeApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存喜欢数据，如果没有查询到就添加，查询到不喜欢的数据就修改
     * @param likeUserId
     * @param userId
     * @param isLike
     * @return
     */
    @Override
    public Boolean save(Long likeUserId, Long userId, boolean isLike) {

        try {
            Criteria critera = Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId);
            Query query = Query.query(critera);
            UserLike userLike = mongoTemplate.findOne(query, UserLike.class);
            if(userLike == null){
                // 不存在就保存
                userLike = new UserLike();
                userLike.setUserId(userId);
                userLike.setLikeUserId(likeUserId);
                userLike.setIsLike(isLike);
                userLike.setCreated(System.currentTimeMillis());
                userLike.setUpdated(System.currentTimeMillis());
                mongoTemplate.save(userLike);
            }else {
                // 存在就更新,
                Update update =  Update.update("isLike", isLike)
                        .set("updated", System.currentTimeMillis()); // 设置更新时间
                mongoTemplate.updateFirst(query, update, UserLike.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
